<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" label-width="100px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="生产领料单号" name="code">
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入生产领料单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<view class="hint-text">只有“已审核”状态的生产工单，才会出现在下拉框中</view>
					<uni-forms-item label="生产单号" name="order" required>
						<uni-data-select mode="underline" placeholder="请选择生产单" v-model="form.order" :localdata="order_list"
							:clear="false" :disabled="pageInfo.type == 'edit'" @change="order_change" />
					</uni-forms-item>
					<uni-forms-item label="领料人" name="get_user_id" required>
						<uni-data-select mode="underline" placeholder="请选择领料人" v-model="form.get_user_id" :localdata="staff_list"
							:clear="false" :disabled="pageInfo.type == 'edit'" />
					</uni-forms-item>
					<uni-forms-item label="备注：" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
				<view class="b-con">
					<u-cell-group :border="false">
						<u-cell :isLink="true" :border="false" :title="`产品数量（${form.product_list.length}）`"
							@click="car_popupShow = true">
							<view slot="value" class="cell-text">点击查看 </view>
						</u-cell>
					</u-cell-group>
				</view>
			</view>
			<custom-popup :popupShow="car_popupShow" mode="bottom" :title="'生产领料'"
				@close="car_popupShow = false" height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false"
					v-model="form.product_list" @query="queryList_car">
					<template #top>
						<view class="zpagin_top">
							<view class="search">
								<view class="hint-text">本期领料数量应在 0 和 (领料数量 - 已发料数量) 之间，且不能大于仓库库存</view>
							</view>
						</view>
					</template>
					<uni-card v-for="(item, pindex) in form.product_list" :key="pindex" margin="5px" spacing="0"
						:title="item.name" :sub-title="item.code">
						<view class="ctent">规格：{{ item.specification }}</view>
						<view class="con">
							<view class="ctent">基本单位：{{ item.unit_main }}</view>
							<view class="ctent">生产数量：{{ item.product_num }}</view>
						</view>
						<view style="background-color: #f2f5f9;">
							<uni-card v-for="(val, cindex) in item.children" :key="cindex" margin="5px" spacing="0" :title="val.name"
								:sub-title="val.code">
								<view class="ctent">规格：{{ val.specification }}</view>
								<view class="con">
									<view class="ctent">基本单位：{{ val.unit_main }}</view>
									<view class="ctent">损耗率(%)：{{ val.loss }}</view>
								</view>
								<view class="con">
									<view class="ctent">BOM量：{{ val.bom_num }}</view>
									<view class="ctent">领料数量：{{ val.num }}</view>
								</view>
								<view class="ctent">已领料数量：{{ val.up_num }}</view>
								<uni-forms-item label="领料仓库：" :name="`product_list[${pindex}].children[${cindex}].warehouse`" required
									:rules="[{ required: true, errorMessage: `请选择【${val.name}】的领料仓库` }]">
									<uni-data-select mode="underline" placeholder="请选择领料仓库" v-model="val.warehouse"
										:localdata="getWarList(val.warehouse_list)" :clear="false"
										@change="handleWareChange($event, val)" />
								</uni-forms-item>
								<view class="con">
									<view class="ctent" style="flex: none;">本期领料数量：</view>
									<custom-num-box v-model="val.now_num" :min="0" @change="changeNum($event, val)"
										:asyncChange="true"></custom-num-box>
								</view>
							</uni-card>
						</view>
					</uni-card>
					<template #bottom>
						<view style="padding: 30rpx 20rpx 30rpx;background-color: #fff;border-top:2px solid #e9e9e9;">
							<u-button type="primary" text="提交" @click="save"></u-button>
						</view>
					</template>
				</z-paging>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import pMaterialApi from '../../../api/production/p_material'
import { generateCode, debounce } from '@/utils/index.js';

//页面标题
const pageInfo = reactive({
	navbarTitle: '生产领料单',
	type: '',
	edit_id: null,
});

onLoad(option => {
	get_order_list()
	get_staff_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(修改)`
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(新增)`
		form.code = generateCode('MT')
	}
})

//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('MT')
	}
}

const refForm = ref(null)
const form = reactive({
	code: '',
	order: null,
	get_user_id: '',
	desc: '',
	product_list: []
})
const fields = Object.keys(form)
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入报价单号' }] },
	order: { rules: [{ required: true, type: 'number', errorMessage: '请选择生产单' }] },
	get_user_id: { rules: [{ required: true, type: 'number', errorMessage: '请选择领料人' }] },
}

function get_detail(id) {
	pMaterialApi.production_issue_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		Object.assign(form, record)
		form.product_list = res.table_data.map(v => {
			v.children = v.children.map(k => {
				k.inventory = k.warehouse_list.find(v => v.id == k.warehouse).inventory
				return k
			})
			return v
		})
	})
}

function order_change(v) {
	form.product_list = []
	pMaterialApi.get_production_order_product({ order__id: v }).then(res => {
		const data = res.results
		form.product_list = data.map(v => {
			const boms = v.order_product_boms
			const children_list = boms.map(k => {
				const stock_list = k.bom.stock_info
				const warehouse_list = stock_list.map(j => ({
					id: j.warehouse_id,
					info: j.warehouse_name + '【' + j.unit_info + '】',
					inventory: j.inventory
				}))
				return {
					id: k.bom.id,
					id_info: 'bom_' + k.bom.id,
					type: 'bom',
					code: k.bom.code,
					name: k.bom.name,
					specification: k.bom.specification,
					unit_main: k.bom.unit_main,
					loss: k.bom.loss,
					bom_num: k.bom_num,
					product_num: '-',
					num: k.num,
					up_num: k.up_num,
					now_num: 0,
					warehouse_list: warehouse_list,
					warehouse: null,
					inventory: null
				}
			})

			return {
				id: v.product.id,
				id_info: 'product_' + v.product.id,
				order_product_id: v.id,
				type: 'product',
				code: v.product.code,
				name: v.product.name,
				specification: v.product.specification,
				unit_main: v.product.unit_main,
				loss: '-',
				bom_num: '-',
				product_num: v.num,
				num: '-',
				up_num: '-',
				warehouse_list: '-',
				now_num: '-',
				children: children_list
			}
		})
	})
}
function getWarList(list) {
	return list.map(v => ({
		text: v.info, value: v.id, inventory: v.inventory
	}))
}
function changeNum(e, row) {
	if (!row.warehouse) {
		return uni.$u.toast('请选择仓库')
	}
	if (e.value > row.inventory) {
		row.now_num = row.inventory
		return uni.$u.toast('领料数不能超过库存数')
	}
	if (e.value > row.num - row.up_num) {
		row.now_num = row.num - row.up_num
		return uni.$u.toast('本期领料数不能超过(领料数 - 已发料数)')
	}
	row.now_num = e.value
}
function handleWareChange(v, row) {
	const obj = row.warehouse_list.find(k => k.id == v)
	row.inventory = obj.inventory
	if (row.now_num > row.inventory) {
		row.now_num = row.inventory
	}
}

const order_list = ref([])
function get_order_list() {
	const params = { page: 1, page_size: 99999, status: 2 };
	pMaterialApi.get_production_order(params).then(res => {
		order_list.value = res.results.map(v => ({
			text: v.code,
			value: v.id
		}))
	})
}

const staff_list = ref([])
function get_staff_list() {
	const params = { page: 1, page_size: 99999 };
	pMaterialApi.get_staff(params).then(res => {
		staff_list.value = res.results.map(v => ({
			text: v.full_name,
			value: v.id
		}))
	})
}

//提交操作
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		if (pageInfo.type == 'add') {
			pMaterialApi.post_production_issue(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			pMaterialApi.patch_production_issue(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})
}

const paging_car = ref(null)
const car_popupShow = ref(false)
function queryList_car() {
	paging_car.value.complete(form.product_list);
}
//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('w_out_product:refresh')
		}
	})
}
</script>

<style lang="scss" scoped></style>